/*
Author: Dave Lenz
Creation date: 24 jun 2009
 */
package nl.ypmits.utils.as3.bitmap.bitmapsequence {
	import nl.ypmits.utils.as3.bitmap.bitmapsequence.vo.BitmapSequenceVO;
	import nl.ypmits.utils.as3.bitmap.BitmapConverter;

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	public class BitmapSequence extends Sprite{
		private var _smoothing : Boolean = false;
		private var _loop : Boolean = false;
		private var _loopBackAndForth : Boolean = false;
		private var _align : String; // TODO: Implementeren
		private var timer : Timer;
		private var frames : Array = [];
		private var _bitmap : Bitmap = new Bitmap( );
		private var currentframe : int = 0;

		public function BitmapSequence( )
		{
			addChild( bitmap );
		}

		
		public function addItem( bitmapsequenceVO : BitmapSequenceVO ) : void
		{
			var bm : Bitmap = new Bitmap( );
			if( bitmapsequenceVO.obj is Bitmap ) {
				bm = Bitmap( bitmapsequenceVO.obj );
			} else if ( bitmapsequenceVO.obj is BitmapData ) {
				bm.bitmapData = BitmapData( bitmapsequenceVO.obj );
			} else {
				bm = BitmapConverter.convertToBitmap( bitmapsequenceVO.obj, false );
			}
			frames.push( bm );
		}

		
		public function start( interval : Number = 50 ) : void
		{
			timer = new Timer( interval, frames.length );
			timer.addEventListener( TimerEvent.TIMER, nextFrame );
			timer.start( );
		}

		
		public function stop() : void
		{
			timer.stop( );
			timer.reset( );
			timer = null;
		}

		
		private function nextFrame( event : TimerEvent ) : void
		{
			bitmap.bitmapData = Bitmap( frames[ currentframe ] ).bitmapData;
			bitmap.x = -( bitmap.width * .5);
			bitmap.y = -( bitmap.height * .5);
			bitmap.smoothing = _smoothing;
			
			if( currentframe == frames.length - 1) 
			{
				currentframe = 0;
				_loop ? start( ) : stop( );
			} 
			else 
			{
				currentframe++;
			}
		}

		
		public function set smoothing(smoothing : Boolean) : void
		{
			_smoothing = smoothing;
		}

		
		public function set loop(loop : Boolean) : void
		{
			_loop = loop;
		}

		
		public function set align(align : String) : void
		{
			_align = align;
		}

		
		public function set loopBackAndForth(loopBackAndForth : Boolean) : void
		{
			_loopBackAndForth = loopBackAndForth;
		}
		
		
		public function get bitmap() : Bitmap
		{
			return _bitmap;
		}
	}
}
